import 'package:flutter/services.dart';
import 'package:get_storage/get_storage.dart';
import 'package:yun/event/change_mode_event.dart';
import 'package:yun/event/open_door_event.dart';
import 'package:yun/event/start_inventory_event.dart';
import 'package:yun/http/http_helper.dart';

import '../entity/current_task_entity.dart';
import '../event/download_url_event.dart';
import '../event/start_read_block_event.dart';
import '../event/voice_change_event.dart';
import '../main.dart';
import '../serial/send_helper.dart';
import 'mqtt.dart';

class ResultHandler{

  handler(topic,data) async {
    var cmd = data['cmd'];
    var uuid = data['uuid'];
    var tradeNo = data['trade_no'];

    //设备状态查询
    if(cmd == '100001' ){
      currentTask.uuids[Task.checkStatus] = uuid;
      currentTask.tradeNos[Task.checkStatus] = tradeNo;
      hfSerialPortHelper.sendData(checkStatus());
    }
    //设备RFID查询时的轮循次数
    if(cmd == '700000'){
      currentTask.uuids[Task.scanTime] = uuid;
      currentTask.tradeNos[Task.scanTime] = tradeNo;
      settingEntity.count = data['count'];
      final box = GetStorage();
      box.write('setting_entity', settingEntity.toJson());
      mqttHelper.push(setScanTime(uuid: currentTask.uuids[Task.scanTime], trade_no: currentTask.tradeNos[Task.scanTime]));
    }
    //RFID筛选
    if(cmd == '111111'){
      var count = data['count'];
      var state = data['state'];
      currentTask.uuids[Task.inventory] = uuid;
      currentTask.tradeNos[Task.inventory] = tradeNo;
      currentTask.remarks[Task.inventoryState] = state;
      currentTask.remarks[Task.cmd] = cmd;
      if(count is int){
        eventFactory.fire(StartInventoryEvent(count));
      }else{
        eventFactory.fire(StartInventoryEvent(null));
      }

    }
    //RFID查询
    if(cmd == '101001'){
      var state = data['state'];
      currentTask.uuids[Task.inventory] = uuid;
      currentTask.tradeNos[Task.inventory] = tradeNo;
      currentTask.remarks[Task.inventoryState] = state;
      currentTask.remarks[Task.cmd] = cmd;
      eventFactory.fire(StartInventoryEvent(null));
    }
    //开门
    if(cmd == '101002'){
      currentTask.uuids[Task.door] = uuid;
      currentTask.tradeNos[Task.door] = tradeNo;
      eventFactory.fire(OpenDoorEvent());
    }
    //开关灯
    if(cmd == '102001'){
      var lamp = data['lamp'];
      var state = data['state'];
      currentTask.uuids[Task.light] = uuid;
      currentTask.tradeNos[Task.light] = tradeNo;
      currentTask.remarks[Task.lightLamp] = lamp;
      currentTask.remarks[Task.lightState] = state;

      if(lamp == 1){
        // var state = currentTask.remarks[Task.lightState];
        if(state == 0){
          hfSerialPortHelper.sendData(closeLight());
        }else{
          hfSerialPortHelper.sendData(openLight());
        }
      }
      if(lamp == 2){
        // var state = currentTask.remarks[Task.lightState];
        if(state == 0){
          hfSerialPortHelper.sendData(closeLight2());
        }else{
          hfSerialPortHelper.sendData(openLight2());
        }
      }
      mqttHelper.push(sendLight(uuid: currentTask.uuids[Task.light],
        trade_no: currentTask.tradeNos[Task.light],
        state: currentTask.remarks[Task.lightState],
        lamp:  currentTask.remarks[Task.lightLamp],
      ));

      // eventFactory.fire(StartLightEvent());
    }
    //查询设备扇区
    if(cmd == '103002'){
      var rfid = data['rfid'];
      currentTask.remarks[Task.readBlockData] = rfid;
      currentTask.uuids[rfid] = uuid;
      currentTask.tradeNos[rfid] = tradeNo;
      eventFactory.fire(StartReadBlockEvent());
    }
    //设备语音播报
    if(cmd == '105001'){
      var voice = data['voice'];
      currentTask.uuids[Task.voice] = uuid;
      currentTask.tradeNos[Task.voice] = tradeNo;
      eventFactory.fire(VoiceChangeEvent(0));
      tts.speak(voice);
      mqttHelper.push(sendVoice(uuid: currentTask.uuids[Task.voice],
        trade_no: currentTask.tradeNos[Task.voice],
      ));

    }
    //设置音量
    if(cmd == '105002'){
      currentTask.uuids[Task.volume] = uuid;
      currentTask.tradeNos[Task.volume] = tradeNo;
      mqttHelper.push(volume(uuid: currentTask.uuids[Task.volume], trade_no: currentTask.tradeNos[Task.volume]));
      var horn = data['horn'];
      var vol = data['vol'];

      if(vol == 1 ){
        settingEntity.adVolume = horn/10;
        eventFactory.fire(VoiceChangeEvent(settingEntity.adVolume??0.2));
      }else{
        settingEntity.tipVolume = horn/10;
        tts.volume(settingEntity.tipVolume);
      }
      final box = GetStorage();
      box.write('setting_entity', settingEntity.toJson());

    }
    //设备重启
    if(cmd == '200000'){
      currentTask.uuids[Task.restart] = uuid;
      // currentTask.tradeNos[Task.restart] = tradeNo;
      mqttHelper.push(sendRestart(uuid: currentTask.uuids[Task.restart]));
      Future.delayed(const Duration(seconds: 1),() async {
        await const MethodChannel('toAndroid').invokeMethod('restart');
      });
      // eventFactory.fire(RestartEvent());
    }

    //屏幕休眠
    if(cmd == '200010'){
      currentTask.uuids[Task.checkScreenOff] = uuid;
      currentTask.tradeNos[Task.checkScreenOff] = tradeNo;
      settingEntity.screen = 0;
      final box = GetStorage();
      box.write('setting_entity', settingEntity.toJson());
      mqttHelper.push(sendScreenOff(uuid: currentTask.uuids[Task.checkScreenOff], trade_no: currentTask.tradeNos[Task.checkScreenOff]));
      await const MethodChannel('toAndroid').invokeMethod('checkScreenOff');
      // eventFactory.fire(CheckScreenEvent(true));
    }
    //唤醒屏幕
    if(cmd == '200011'){
      currentTask.uuids[Task.checkScreenOn] = uuid;
      currentTask.tradeNos[Task.checkScreenOn] = tradeNo;
      settingEntity.screen = 1;
      final box = GetStorage();
      box.write('setting_entity', settingEntity.toJson());
      mqttHelper.push(sendScreenOn(uuid: currentTask.uuids[Task.checkScreenOn], trade_no: currentTask.tradeNos[Task.checkScreenOn]));
      await const MethodChannel('toAndroid').invokeMethod('checkScreenOn');
      // eventFactory.fire(CheckScreenEvent(false));
    }
    //定时开关机
    if(cmd == '200001'){
      currentTask.uuids[Task.alarm] = uuid;
      currentTask.tradeNos[Task.alarm] = tradeNo;
      mqttHelper.push(alarm(uuid: currentTask.uuids[Task.alarm], trade_no: currentTask.tradeNos[Task.alarm]));
      settingEntity.onTime = data['time']['on'];
      settingEntity.offTime = data['time']['off'];
      final box = GetStorage();
      box.write('setting_entity', settingEntity.toJson());
      const MethodChannel('toAndroid').invokeMethod('alarm',{'onTime':data['time']['on'],'offTime':data['time']['off']});
      // eventFactory.fire(CheckScreenEvent(false));
    }
    //h5
    if(cmd == '800000'){
      currentTask.uuids[Task.h5] = uuid;
      currentTask.tradeNos[Task.h5] = tradeNo;
      mqttHelper.push(h5(uuid: currentTask.uuids[Task.h5], trade_no: currentTask.tradeNos[Task.h5]));
      settingEntity.mode = 1;
      settingEntity.url = data['url'];
      final box = GetStorage();
      box.write('setting_entity', settingEntity.toJson());
      eventFactory.fire(ChangeModeEvent());
    }
    //ad
    if(cmd == '800001'){
      currentTask.uuids[Task.ad] = uuid;
      currentTask.tradeNos[Task.ad] = tradeNo;
      mqttHelper.push(ad(uuid: currentTask.uuids[Task.ad], trade_no: currentTask.tradeNos[Task.ad]));
      settingEntity.mode = 0;
      final box = GetStorage();
      box.write('setting_entity', settingEntity.toJson());
      eventFactory.fire(ChangeModeEvent());
    }
    //软件升级
    if(cmd == '500000'){
      currentTask.uuids[Task.update] = uuid;
      currentTask.tradeNos[Task.update] = tradeNo;
      currentTask.updateVersion = data['version'];
      int v = int.parse(data['version'].replaceAll('.', ''));
      int currentV = int.parse(currentVersion.replaceAll('.', ''));
      if(v > currentV){
        HttpHelper.instance.downLoadApk(data['url']);
        mqttHelper.push(update(uuid: currentTask.uuids[Task.update], trade_no: currentTask.tradeNos[Task.update], version: '${data['version']}', state: '1'));

      }
    }

    //广告下载
    if(cmd == '400000'){
      currentTask.uuids[Task.downloadUrl] = uuid;
      currentTask.tradeNos[Task.downloadUrl] = tradeNo;
      String replaceUrl = data['url'].toString().replaceAll('[[', '').replaceAll(']]', '').replaceAll('], [', '__');
      print('replaceUrl = $replaceUrl');
      List<String> urls = replaceUrl.split('__');
      print('urls = $urls');

      List<String> listData = [];
      for (String element in urls) {
        print('element = $element');

        var list = element.split(',');
        print('list = $list');

        listData.add(list[0]);
      }
      print('listData = $listData');
      currentTask.urls = listData;
      eventFactory.fire(DownloadUrlEvent());
    }


  }

}